import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

interface stateProps {
  data: DataType[]
  setData: (newData: DataType[]) => void
  searchText: string
  setSearchText: (newSearchText: string) => void
  error: string
  setError: (newError: string) => void
  id: number
  setId: (newId: number) => void
  isMove: boolean
  setIsMove: (newIsMove: boolean) => void
  shortcut: string
  setShortcut: (newShortcut: string) => void
  webPageList: DataType[]
  setWebPageList: (newWebPageList: DataType[]) => void
  selectPageList: number[]
  setSelectPageList: (newSelectPageList: number[]) => void
  selfStarting: boolean
  setSelfStarting: (newSelfStarting: boolean) => void
}

export const useStore = create<stateProps>()(
  persist(
    (set) => ({
      data: [],
      setData: (newData) => set({ data: newData }),
      searchText: '',
      setSearchText: (newSearchText) => set({ searchText: newSearchText }),
      error: '',
      setError: (newError) => set({ error: newError }),
      id: -1,
      setId: (newId) => set({ id: newId }),
      isMove: false,
      setIsMove: (newIsMove: boolean) => set({ isMove: newIsMove }),
      shortcut: '',
      setShortcut: (newShortcut: string) => set({ shortcut: newShortcut }),
      webPageList: [
        {
          id: -1,
          title: '谷歌搜索',
          content: 'https://www.google.com',
          type: 1
        },
        {
          id: -2,
          title: '百度搜索',
          content: 'https://www.baidu.com',
          type: 2
        },
        {
          id: -3,
          title: '必应搜索',
          content: 'https://cn.bing.com',
          type: 3
        }
      ],
      setWebPageList: (newWebPageList: DataType[]) => set({ webPageList: newWebPageList }),
      selectPageList: [-1, -2, -3],
      setSelectPageList: (newSelectPageList: number[]) =>
        set({ selectPageList: newSelectPageList }),
      selfStarting: false,
      setSelfStarting: (newSelfStarting: boolean) => set({ selfStarting: newSelfStarting })
    }),
    {
      name: 'codeSnippetsStorage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        shortcut: state.shortcut,
        selectPageList: state.selectPageList,
        selfStarting: state.selfStarting
      })
    }
  )
)
